import { useColorMode, useCycleList } from '@vueuse/core'

import '@/styles/common/view-transition.css'

const mode = useColorMode({
  emitAuto: true,
  storageKey: 'b-theme-appearance',
})

const list = ['auto', 'dark', 'light']

export const { state, next } = useCycleList(list, { initialValue: mode })

watchEffect(() => mode.value = state.value)

export const isDark = computed(() => {
  return state.value === 'auto' ? mode.system.value === 'dark' : state.value === 'dark'
})

export async function toggleDarkWithTransition(e) {
  if (!document.startViewTransition) {
    next()
    return
  }

  const i = list.indexOf(state.value)
  const length = list.length
  const index = ((i + 1) % length + length) % length
  const value = list[index]

  if ((value === 'auto' && mode.system.value === state.value) || (state.value === 'auto' && mode.system.value === value)) {
    next()
    return
  }

  const x = e.clientX
  const y = e.clientY
  const radius = Math.hypot(Math.max(x, innerWidth - x), Math.max(y, innerHeight - y))

  const transition = document.startViewTransition(() => next())
  await transition.ready

  const clipPath = [
    `circle(0 at ${x}px ${y}px)`,
    `circle(${radius}px at ${x}px ${y}px)`,
  ]

  document.documentElement.animate(
    {
      clipPath: isDark.value ? clipPath.reverse() : clipPath,
    },
    {
      duration: 400,
      easing: 'ease-in',
      fill: 'both',
      pseudoElement: isDark.value ? '::view-transition-old(root)' : '::view-transition-new(root)',
    },
  )
}
